package com.sigmazero13.bgjeeves;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.sigmazero13.bgjeeves.GameImageService.LocalBinder;
import com.sigmazero13.bgjeeves.db.UtilDbHelper;
import com.sigmazero13.bgjeeves.model.GameInfo;
import com.sigmazero13.bgjeeves.model.GameInfoCustom;

public class GameInfoView extends Activity {
	GameInfo game;
	
	public static final int CUSTOM_EDIT = 1;
	
	TextView gameField;
	TextView ratingField;
	TextView lengthField;
	TextView playersField;
	ImageView gameImage;
	
	GameImageService mService;
	boolean mBound = false;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.game_info);
		
		Bundle bundle = getIntent().getExtras();
		Integer gameId = bundle.getInt("game_id", 0);
		
		game = ((BoardGameUtilsApp)getApplication()).getDbHelper().selectSingleGame(gameId);
		
		gameField = (TextView)this.findViewById(R.id.game_name);
		ratingField = (TextView)this.findViewById(R.id.game_rating);
		lengthField = (TextView)this.findViewById(R.id.game_length);
		playersField = (TextView)this.findViewById(R.id.game_players);
		gameImage = (ImageView)this.findViewById(R.id.game_image);
		
		gameField.setText(game.getName());
		ratingField.setText(game.getBggRating().toString());
		lengthField.setText(game.getBggLength().toString() + " mins");
		playersField.setText(game.getNumPlayersString());
		gameImage.setImageDrawable(new BitmapDrawable());
		
		Button playButton = (Button)this.findViewById(R.id.button_game_plays);
		playButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(GameInfoView.this, PlayList.class);
    			i.putExtra("game_id", game.getGameId());
    			startActivity(i);
			}
		});
		
		Button recordButton = (Button)this.findViewById(R.id.button_record_play);
		recordButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(GameInfoView.this, RecordGameConfig.class);
				i.putExtra("game_id", game.getGameId());
				startActivity(i);
			}
		});
		
		Button teamReportButton = (Button)this.findViewById(R.id.button_win_report);
		teamReportButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(GameInfoView.this, PlayReportView.class);
				i.putExtra("game_id", game.getGameId());
				startActivity(i);
			}
		});
		
		Button teamListButton = (Button)this.findViewById(R.id.button_game_teams);
		teamListButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(GameInfoView.this, TeamList.class);
				i.putExtra("game_id", game.getGameId());
				startActivity(i);
			}
		});
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		Intent intent = new Intent(this, GameImageService.class);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		try {
			unbindService(mConnection);
		} catch (Exception e) {
			Log.d("GameInfoView.onPause", e.getMessage());
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.game_info_menu, menu);
		return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case R.id.edit_custom:
			Intent i = new Intent(GameInfoView.this, GameInfoCustomEdit.class);
			i.putExtra("game_id", game.getGameId());
			startActivityForResult(i, CUSTOM_EDIT);
			break;
		}
		
		return true;
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        
        switch (requestCode) {
        case CUSTOM_EDIT:
        	if (resultCode == RESULT_OK) {
        		Bundle bundle = intent.getExtras();
        		Integer min = bundle.getInt("min_players");
        		Integer max = bundle.getInt("max_players");
        		GameInfoCustom newCustom = new GameInfoCustom(game);
        		newCustom.setMinPlayers(min);
        		newCustom.setMaxPlayers(max);
        		boolean modified = false;
        		        		
        		UtilDbHelper mDb = ((BoardGameUtilsApp)getApplication()).getDbHelper();
        		GameInfoCustom custom = game.getCustomInfo();
        		if (custom == null && !newCustom.isEmpty()) {
        			custom = newCustom;
        			game.setCustomInfo(custom);
        			custom.setParentGame(game);
        			modified = true;
        		}
        		if (custom == null || !custom.equals(newCustom)) {
        			game.setCustomInfo(newCustom);
        			newCustom.setParentGame(game);
        			modified = true;
        		}
        		if (modified) {
        			mDb.recordCustomInfo(newCustom);
        		
        			playersField.setText(game.getNumPlayersString());
        			Intent i = new Intent();
        			i.putExtra("modified", true);
        			i.putExtra("game_id", game.getGameId());
        			setResult(RESULT_OK, i);
        		}
        	}
        	break;
        }
	}	
	
	private ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			LocalBinder binder = (LocalBinder) service;
			mService = binder.getService();
			mBound = true;
			
			getImage();
		}
		
		@Override
		public void onServiceDisconnected(ComponentName className) {
			mBound = false;
		}
	};
	
	private void getImage() {
		new ImageTask().execute(game.getGameId());
	}
	
	private class ImageTask extends AsyncTask<Integer, Void, Drawable> {
		@Override
		protected void onPreExecute() {
		}
		
		@Override
		protected Drawable doInBackground(Integer... imageIds) {
			if (mBound) {
				return mService.getThumbnail(imageIds[0]);
			} else {
				return null;
			}
		}
		
		@Override
		protected void onPostExecute(Drawable result) {
			gameImage.setImageDrawable(result);
		}	
	}
}
